package com.jintoufs.web.action.common;

import org.apache.commons.io.FileUtils;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

public abstract class JxlsHandler {
	private static Logger logger = LoggerFactory.getLogger(JxlsHandler.class);

	/**
	 * @description 根据EXCEL模板,获取文件流
	 * @param request
	 * @param templateName
	 *            excel模板
	 * @param results
	 *            数据结果集
	 * @return InputStream
	 * @throws FileNotFoundException
	 */

	public static void report(HttpServletRequest request,
			HttpServletResponse response, String templateName, Object results)
			throws IOException {
		/**
		 * 禁止数据缓存
		 */
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
//		ServletUtils.setDisableCacheHeader(response);
		/**
		 * 设置响应格式
		 */
		response.setContentType("application/vnd.ms-excel;charset=utf-8");

		/**
		 * 获取web容器上下文中EXCEL模板文件路径
		 */
		StringBuilder filePath = new StringBuilder();

		String realPath = request.getServletContext().getRealPath("/report");
		filePath.append(realPath);
		filePath.append(File.separator);
		filePath.append(templateName);

		logger.debug("The excel template path is :{}", realPath);

		File file = FileUtils.getFile(filePath.toString());
		InputStream is = new FileInputStream(file);
		/**
		 * 流操作
		 */
//		OutputStream os = new FileOutputStream(realPath+"/test.xls");
		OutputStream os=response.getOutputStream();
		try {
			Context context = new Context();
			context.putVar("rs", results);
			JxlsHelper.getInstance().processTemplate(is, os, context);
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
			logger.debug(
					"Write data into HSSFWorkbook occur exception,caused by:{}",
					e);
		} finally {
			if (is != null) {
				try {
					is.close();
//					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
}